<template>
  <div class="ent-card shadow-enterprise-md animate-fade-in">
    <div class="ent-card-header flex items-center justify-between">
      <div class="flex items-center">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2 text-primary-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
        </svg>
        <h2 class="text-lg font-medium text-gray-800 dark:text-gray-200">数据可视化</h2>
      </div>
      <div class="flex space-x-2">
        <button
          @click="downloadChart"
          class="ent-btn-ghost text-xs p-1.5"
          title="下载图表"
        >
          <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
          </svg>
        </button>
        <button
          @click="toggleFullscreen"
          class="ent-btn-ghost text-xs p-1.5"
          title="全屏查看"
        >
          <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5v-4m0 4h-4m4 0l-5-5" />
          </svg>
        </button>
      </div>
    </div>
    
    <div class="ent-card-body p-0">
      <!-- 加载状态 -->
      <div v-if="loading" class="flex justify-center items-center p-16">
        <div class="animate-spin rounded-full h-10 w-10 border-t-2 border-b-2 border-primary-500"></div>
      </div>

      <!-- 图表显示 -->
      <div v-else-if="processedChartData" class="p-4">
        <div ref="chartContainer" class="w-full h-[400px]"></div>
      </div>

      <!-- 无图表状态 -->
      <div v-else class="p-8 text-center text-gray-500 dark:text-gray-400">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12 mx-auto mb-4 text-gray-400 dark:text-gray-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
        </svg>
        <p>暂无可视化图表</p>
      </div>
    </div>

    <!-- 全屏模态框 -->
    <div
      v-if="isFullscreen && processedChartData"
      class="fixed inset-0 bg-black bg-opacity-80 flex items-center justify-center z-50"
      @click.self="toggleFullscreen"
    >
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-enterprise-xl p-4 w-11/12 h-5/6 flex flex-col">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-xl font-medium text-gray-800 dark:text-gray-200">数据可视化</h3>
          <button
            @click="toggleFullscreen"
            class="ent-btn-ghost p-1.5"
          >
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        <div ref="fullscreenChartContainer" class="flex-1 w-full"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import Plotly from 'plotly.js-dist-min'

export default {
  name: 'PlotlyChart',
  props: {
    chartData: {
      type: Object,
      default: null
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  setup(props) {
    const chartContainer = ref(null)
    const fullscreenChartContainer = ref(null)
    const isFullscreen = ref(false)
    
    // 处理和规范化图表数据
    const processedChartData = computed(() => {
      if (!props.chartData) return null
      
      try {
        // 检查数据结构
        if (!props.chartData.data && !Array.isArray(props.chartData.data)) {
          // 尝试找到可能的数据属性
          const possibleData = props.chartData.fig || props.chartData.figure || props.chartData.chart
          
          if (possibleData) {
            if (typeof possibleData === 'string') {
              try {
                return JSON.parse(possibleData)
              } catch (e) {
                return createDefaultChart()
              }
            } else {
              return possibleData
            }
          }
          
          // 尝试创建一个默认图表
          return createDefaultChart()
        }
        
        return props.chartData
      } catch (error) {
        return createDefaultChart()
      }
    })
    
    // 创建默认图表
    const createDefaultChart = () => {
      return {
        data: [
          {
            type: 'bar',
            x: ['数据1', '数据2', '数据3', '数据4', '数据5'],
            y: [10, 15, 13, 17, 12],
            marker: {
              color: '#0066c8'
            }
          }
        ],
        layout: {
          title: '默认数据图表',
          showlegend: false
        }
      }
    }

    const renderChart = (container, data) => {
      if (!container || !data) return
      
      try {
        // 确保图表数据格式正确
        let chartDataToRender = data
        
        // 检查数据是否有正确的结构
        if (!data.data || !Array.isArray(data.data)) {
          // 尝试修复数据结构
          if (Array.isArray(data)) {
            // 数据是一个数组，可能是直接的traces数组
            chartDataToRender = {
              data: data,
              layout: { showlegend: true }
            }
          } else if (typeof data === 'object') {
            // 尝试提取可能的数据字段
            const possibleData = data.traces || data.series || data.charts
            if (Array.isArray(possibleData)) {
              chartDataToRender = {
                data: possibleData,
                layout: data.layout || { showlegend: true }
              }
            } else {
              // 无法修复，创建默认图表
              chartDataToRender = createDefaultChart()
            }
          } else {
            // 无法修复，创建默认图表
            chartDataToRender = createDefaultChart()
          }
        }
      
        // 根据当前主题设置图表样式
        const isDarkMode = document.documentElement.classList.contains('dark')
        
        // 使用主题配置
        const layout = {
          ...(chartDataToRender.layout || {}),
          paper_bgcolor: isDarkMode ? 'rgba(31, 41, 55, 0.8)' : 'rgba(255, 255, 255, 0.8)',
          plot_bgcolor: isDarkMode ? 'rgba(31, 41, 55, 0)' : 'rgba(255, 255, 255, 0)',
          font: {
            family: 'Inter, sans-serif',
            color: isDarkMode ? '#e5e7eb' : '#374151'
          },
          margin: { t: 40, r: 20, b: 40, l: 40 },
          xaxis: {
            ...(chartDataToRender.layout?.xaxis || {}),
            gridcolor: isDarkMode ? 'rgba(75, 85, 99, 0.3)' : 'rgba(209, 213, 219, 0.5)',
            zerolinecolor: isDarkMode ? 'rgba(75, 85, 99, 0.5)' : 'rgba(156, 163, 175, 0.5)'
          },
          yaxis: {
            ...(chartDataToRender.layout?.yaxis || {}),
            gridcolor: isDarkMode ? 'rgba(75, 85, 99, 0.3)' : 'rgba(209, 213, 219, 0.5)',
            zerolinecolor: isDarkMode ? 'rgba(75, 85, 99, 0.5)' : 'rgba(156, 163, 175, 0.5)'
          }
        }

        Plotly.newPlot(container, chartDataToRender.data, layout, {
          responsive: true,
          displayModeBar: true,
          displaylogo: false,
          modeBarButtonsToRemove: ['sendDataToCloud', 'lasso2d', 'select2d']
        })
      } catch (error) {
        // 尝试渲染默认图表
        try {
          const defaultData = createDefaultChart()
          Plotly.newPlot(container, defaultData.data, defaultData.layout, {
            responsive: true,
            displayModeBar: true,
            displaylogo: false
          })
        } catch (e) {
          // 渲染失败的情况下什么都不做
        }
      }
    }

    const toggleFullscreen = () => {
      isFullscreen.value = !isFullscreen.value

      if (isFullscreen.value) {
        // 在下一个tick渲染全屏图表
        setTimeout(() => {
          renderChart(fullscreenChartContainer.value, processedChartData.value)
        }, 100)
      }
    }

    const downloadChart = () => {
      if (!chartContainer.value || !processedChartData.value) return

      Plotly.downloadImage(chartContainer.value, {
        format: 'png',
        filename: 'text2sql-chart',
        width: 1200,
        height: 800
      })
    }

    // 监听图表数据变化
    watch(() => props.chartData, (newData) => {
      if (processedChartData.value && chartContainer.value) {
        renderChart(chartContainer.value, processedChartData.value)
      }
    }, { deep: true })

    // 组件挂载后渲染图表
    onMounted(() => {
      if (processedChartData.value && chartContainer.value) {
        renderChart(chartContainer.value, processedChartData.value)
      }
    })

    return {
      chartContainer,
      fullscreenChartContainer,
      isFullscreen,
      processedChartData,
      toggleFullscreen,
      downloadChart
    }
  }
}
</script>
